﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Fsxm.LispEdit;
using FastColoredTextBoxNS;
using System.Text.RegularExpressions;
using System.IO;
using System.Windows.Forms;
using Plugin_RmComment.Properties;


[assembly: PluginClass(typeof(Plugin_RmComment.RemoveComment))]
namespace Plugin_RmComment
{
    public class RemoveComment : Plugin
    {

        public override void Start()
        {
            var item2 = AddMenuItem("清除注释", null);
            item2.Click += Item2_Click;
            item2.ShortcutKeys = Keys.Control | Keys.K;

            foreach (Control itxem in EditApp.Controls)
            {
                if (itxem is ToolStrip)
                {
                    ToolStrip FstoolStrip = itxem as ToolStrip;
                    var item3 = FstoolStrip.Items.Add("清除注释(ctrl+K)");
                    item3.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText;
                    item3.Image = Resources.ico2;
                    item3.Click += Item2_Click;
                    break;
                }
            }
        }
        private void Item2_Click(object sender, EventArgs e)
        {
            var edit = ActivateEdit;
            if (edit == null) return;
            string strtmp=edit.Text;
            strtmp = ClearMultilineComment(strtmp);
            edit.Text = ClearSingleComment(strtmp);
        }
        /// <summary>
        /// 清除多行注释
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private string ClearMultilineComment(string text)
        {
            //匹配多行注释
            string pattern = @"(;\|)([\s\S]*?)(\|;)";
            string tmp = Regex.Replace(text, pattern, "", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            return tmp;
        }
        /// <summary>
        /// 清除单行注释
        /// </summary>
        /// <param name="text">lisp文本</param>
        /// <returns>返回清除单行注释后的文本</returns>
        private string ClearSingleComment(string text)
        {
            //正则说明 https://blog.csdn.net/bravezhe/article/details/8301569
            //正则表达式在线测试 https://regex101.com/r/uJIth7/1/

            //匹配并清理注释前的空白
            string pattern = @"(^[ \t]*;.*$)|((?<!^)[ \t]*;+[^""\n]*$)";

            //不匹配且不清理注释前的空白
            //string pattern = @"((?<=^[ \t]*)(;.*$))|((?<!^);+[^""\n]*$)";

            string tmp = Regex.Replace(text, pattern, "", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            return Regex.Replace(tmp, @"\n\s*\n", "\r\n", RegexOptions.IgnoreCase | RegexOptions.Multiline);
        }

    }

}
